Skip to main content

03 Sliding Window - subarray

Requirement - any array
Core Problem - Find a portion of array which satisfies a certain criteria
Core Logic : Make a window of that size and slide that window till end.

  • For Slicing we do sliced_arr=arr[1:4] this will make a sub array from 1 till 3
  • For looping we do for i in range(len(arr) - k + 1) where k is window size

497

Steps:​

  1. Start with the sum of the first k elements.
  2. Slide the window one element at a time, subtracting the element that goes out of the window and adding the new element.
  3. Keep track of the maximum sum encountered.

Sample Problem:​

Find the maximum sum of a subarray of size k.

  • Input: nums = [2, 1, 5, 1, 3, 2], k = 3
  • Output: 9

LeetCode Problems:​

    1. Maximum Average Subarray I (LeetCode #643)
  1. Longest Substring Without Repeating Characters (LeetCode #3)
  2. Minimum Window Substring (LeetCode #76)